package pkg;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.data.TextConstruct;

public class BaseGroupService {

	public static boolean addNewGroup(String name, String comment,
			BaseEngine engine) {
		if (name == null || comment == null || engine == null)
			return false;
		GoogleBaseEntry entry = new GoogleBaseEntry();
		entry.setTitle(TextConstruct
				.create(TextConstruct.Type.TEXT, name, null));
		entry.getGoogleBaseAttributes().setItemType("System groups");
		entry.setDraft(true);
		entry.getGoogleBaseAttributes().addTextAttribute("comment", comment);
		return engine.insertGoogleBaseEntry(entry);
	}

	public static String printGroupList(BaseEngine engine) {
		StringBuffer out = new StringBuffer();
		out.append("<h2>Lista grup</h2>\n");
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault()
				.getItemsFeedURL());
		query.setStringCustomParameter("Item Type", "System groups");
		GoogleBaseFeed feed = engine.getQueryResult(query);
		if (feed == null)
			return out.toString();

		out.append("<TABLE border=1>\n");
		out.append("\t<tr>\n");
		out.append("\t\t<td>" + "Nazwa grupy" + "</td>\n");
		out.append("\t\t<td>" + "Komentarz" + "</td>\n");
		out.append("\t<tr>\n");
		for (GoogleBaseEntry entry : feed.getEntries()) {
			if (entry.getGoogleBaseAttributes().getItemType().equals(
					"System groups")) {
				out.append("\t<tr>");
				out.append("\t\t<td>");
				out.append(entry.getTitle().getPlainText());
				out.append("</td>\n");

				out.append("\t\t<td>");
				out.append(entry.getGoogleBaseAttributes().getTextAttribute(
						"comment"));
				out.append("</td>\n");

				out.append("\t</tr>");
			}
		}

		out.append("</TABLE>");
		return out.toString();
	}

	public static String printGroupOptions(BaseEngine engine) {
		StringBuffer out = new StringBuffer();
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault()
				.getItemsFeedURL());
		query.setStringCustomParameter("Item Type", "System groups");
		GoogleBaseFeed feed = engine.getQueryResult(query);
		for (GoogleBaseEntry entry : feed.getEntries()) {
			if (entry.getGoogleBaseAttributes().getItemType().equals(
					"System groups")) {
				out.append("<option value=\"");
				out.append(entry.getId());
				out.append("\">");
				out.append(entry.getTitle().getPlainText());
				out.append("</option>\n");
			}
		}
		return out.toString();
	}

}
